package com.hqd.ch03.v27.tx.transaction.interceptor;

import com.hqd.ch03.v27.config.StringValueResolver;
import com.hqd.ch03.v27.tx.transaction.support.DefaultTransactionDefinition;
import org.apache.commons.lang3.StringUtils;

/**
 * 事务属性
 */
public class DefaultTransactionAttribute extends DefaultTransactionDefinition implements TransactionAttribute {


    private String timeoutString;


    public DefaultTransactionAttribute() {
        super();
    }

    public DefaultTransactionAttribute(TransactionAttribute other) {
        super(other);
    }

    public DefaultTransactionAttribute(int propagationBehavior) {
        super(propagationBehavior);
    }

    public String getTimeoutString() {
        return this.timeoutString;
    }

    public void setTimeoutString(String timeoutString) {
        this.timeoutString = timeoutString;
    }

    @Override
    public boolean rollbackOn(Throwable ex) {
        return (ex instanceof RuntimeException || ex instanceof Error);
    }


    public void resolveAttributeStrings(StringValueResolver resolver) {
        String timeoutString = this.timeoutString;
        if (StringUtils.isNotBlank(timeoutString)) {
            if (resolver != null) {
                timeoutString = resolver.resolveStringValue(timeoutString);
            }
            if (StringUtils.isNotBlank(timeoutString)) {
                try {
                    setTimeout(Integer.parseInt(timeoutString));
                } catch (RuntimeException ex) {
                    throw new IllegalArgumentException(
                            "Invalid timeoutString value \"" + timeoutString + "\" - cannot parse into int");
                }
            }
        }
    }

}
